<template>
  <el-dialog
    title="添加合同"
    :visible="rentDialogVisible"
    width="580px"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <!-- 表单模版 -->
    <div class="form-container">
      <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="rentForm.buildingId" placeholder="请选择">
            <el-option
              v-for="item in list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="rentTime">
          <el-date-picker
            v-model="rentForm.rentTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId">
          <el-upload
            ref="uploadFileRef"
            action="#"
            :http-request="onUploadFile"
            :before-upload="onBeforeUpload"
          >
            <el-button size="small" type="primary" plain>上传合同文件</el-button>
            <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button size="mini" type="primary" @click="onSubmit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { addRentAPI, getBuildingAPI, uploadAPI } from '@/api/enterprise'
export default {
  name: 'AddRentDialog',
  props: {
    rentDialogVisible: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          // console.log(time)
          // 禁止选择今天之前的日期
          // console.log()
          return time.getTime() < Date.now() - 86400 * 1000
        }
      },
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      list: [] // 保存可租赁楼宇列表
    }
  },
  methods: {
    // 当表单提交时
    async onSubmit() {
      await this.$refs.addForm.validate()
      try {
        // await addRentAPI()
        // 处理参数
        this.rentForm.startTime = this.rentForm.rentTime[0]
        this.rentForm.endTime = this.rentForm.rentTime[1]
        delete this.rentForm.rentTime
        // console.log(this.rentForm)
        await addRentAPI(this.rentForm)
        // 关闭dialog
        this.$emit('update:rentDialogVisible', false)
        // 更新数据 initData 在父组件里面 在子组件里面访问到父组件的方法  this.$parent
        // console.log(this.$parent)
        this.$parent.initData()
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    // 对上传的文件进行校验
    onBeforeUpload(file) {
      // console.log(file)
      const fileType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
      const isType = fileType.includes(file.type)
      if (!isType) {
        this.$message.error('上传合同只能是 doc/docx/pdf 格式!')
      }
      // 文件的大小 文件不能超过5M 1M = 1024kb  1kb = 1024字节
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }

      return isType && isLt5M
    },
    // 上传合同
    async onUploadFile(obj) {
      // console.log(obj)
      const file = obj.file
      // 文件上传需要使用到 FormData 构造函数
      const fd = new FormData()
      // 需要调用 fd.append()方法
      fd.append('file', file)
      fd.append('type', 'contract')
      // 发送ajax请求
      try {
        const res = await uploadAPI(fd)
        // console.log(res)
        this.rentForm.contractId = res.data.id
        this.rentForm.contractUrl = res.data.url
        // 上传成功后需要对 字段 清空提示
        this.$refs.addForm.validateField('contractId')
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    },
    // 关闭 dialog
    closeDialog() {
      // 子向父传值
      this.$emit('update:rentDialogVisible', false)
      // 将表单的数据清空
      this.$refs.addForm.resetFields()
      this.rentForm.contractUrl = ''
      // 清空已上传的文件列表
      this.$refs.uploadFileRef.clearFiles()
    },
    // 获取租赁的楼宇
    async getBuilding() {
      try {
        const res = await getBuildingAPI()
        // console.log(res)
        this.list = res.data
      } catch (error) {
        if (error.response) {
          this.$message.error(error.response.data.msg)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form-container{
  padding:0px 80px;
}
</style>
